package com.fmm.easy;

import java.util.Arrays;

public class DefuseBomb {

    public static int[] defuseBomb(int[] code, int k) {
        int[] result = new int[code.length];
        int codeLength = code.length;
        int codeSum = Arrays.stream(code).sum();
        for (int i = 0; i < codeLength; i++) {
            // 无论是 k >= 0 还是 k < 0 的情况下，都分为 2 部分，一部分是循环次数 * 数组总和，另一部分是不满循环的数组总和
            if (k >= 0) {
                int s = 0;
                for (int n = 1; n <= k % codeLength; n++) {
                    s = s + code[(i + n) % codeLength];
                }
                // 结果为 循环次数 * 数组总和 + 不满循环的数组总和
                result[i] = k/codeLength * codeSum + s;
            } else {
                int s = 0;
                for (int n = 1; n <= Math.abs(k) % codeLength; n++) {
                    s = s + code[(i + Math.abs(n - codeLength)) % codeLength];
                }
                // 结果为 循环次数 * 数组总和 + 不满循环的数组总和
                result[i] = Math.abs(k)/codeLength * codeSum + s;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] code = {5, 7, 1, 4};
        int k = 3;
        System.out.println(Arrays.toString(defuseBomb(code, k)));

        code = new int[] {1, 2, 3, 4};
        k = 0;
        System.out.println(Arrays.toString(defuseBomb(code, k)));

        code = new int[] {2, 4, 9, 3};
        k = -2;
        System.out.println(Arrays.toString(defuseBomb(code, k)));
    }
}
